package studio.raptor.dispatcher.common.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import studio.raptor.dispatcher.common.exception.ConfigException;

/**
 * @author jack
 * @since 1.0
 */
public class ConfigUtil {

  public static Map<String, String> getAllXMlName(String xml) {

    Map<String, String> result = new HashMap<>();

    try {
      Document document = DocumentHelper.parseText(xml);
      Element root = document.getRootElement();
      for (Iterator it = root.elementIterator(); it.hasNext(); ) {
        Element element = (Element) it.next();
        String code = element.attribute("code").getText();
        String fileName = element.attribute("resource").getText();
        result.put(code, fileName);
      }
    } catch (DocumentException e) {
      throw new ConfigException("parse xml error",e);
    }
    return result;
  }

  public static List<String> getAllPropertiesName(String xml) {

    List<String> result = new ArrayList<>();

    try {
      Document document = DocumentHelper.parseText(xml);
      Element root = document.getRootElement();
      for (Iterator it = root.elementIterator(); it.hasNext(); ) {
        Element element = (Element) it.next();
        String fileName = element.attribute("resource").getText();
        result.add(fileName);
      }
    } catch (DocumentException e) {
      throw new ConfigException("parse xml error",e);
    }
    return result;
  }

}
